import io
import os
import re

from pypinyin import lazy_pinyin

from util.database.mysql import MyMysql
from util.database.oracle import MyOracle
from util.comm.path import getPath
from util.comm.msg_util import msg


def select_dict(field, config):
    database_type = config['type']
    if database_type == 'oracle':
        field_list = MyOracle().search(config, config['sql'] % field)
    elif database_type == 'mysql':
        field_list = MyMysql().search(config, config['sql'] % field)
    else:
        msg('数据库类型【%s】配置错误' % database_type)
        return None
    if field_list:
        if field_list == "0":
            return None
        return generate(field, field_list)
    else:
        msg("字典【%s】查询不存在" % field)
        return None


def generate_enum_java(field, field_list):
    desc = field
    file = to_camel_case(field)
    buf = io.StringIO()
    for row in field_list:
        buf.write('\t%s("%s", "%s"),\n' % (get_initials(row[1]), row[0], row[1].replace('\\', '/')))
    field_txt = buf.getvalue()
    # 调用函数，输入你的文件路径，输出文件路径，需要被替换的字符，替换成的字符
    old_chars = ['@@desc@@', '@@file@@', '@@field@@']
    new_chars = [desc, file, field_txt]
    project_path = getPath()
    in_file_name = os.path.join(project_path, 'dict_modal_file.txt')
    out_file_name = os.path.join(project_path, '%sEnum.java' % file)
    replace_char_in_file(in_file_name, out_file_name, old_chars, new_chars)
    return out_file_name


# 转大驼峰命名
def to_camel_case(s):
    return ''.join(word.capitalize() for word in s.split('_'))


# 获取中文首字母
def get_initials(s):
    name = ''.join([p[0][0].upper() for p in lazy_pinyin(s)])
    return re.sub(r'[^a-zA-Z0-9]', '_', name)


def replace_char_in_file(input_file, output_file, old_chars, new_chars):
    with open(input_file, 'r', encoding='utf-8') as file:
        data = file.read()

    # 替换字符
    for old, new in zip(old_chars, new_chars):
        data = data.replace(old, new)

    with open(output_file, 'w', encoding='utf-8') as file:
        file.write(data)


def generate(field, field_list):
    return generate_enum_java(field, field_list)
